<template>
  <div id="app">
    <!-- 控制区域 -->
    <el-row style="margin-bottom: 10px;">
      <el-col :span="24">
        <!-- 选择模式切换开关 -->
        <el-switch v-model="isMultiSelect" active-text="多选" inactive-text="单选" @change="handleSelectModeChange" />
        <el-button type="primary" @click="addNewRow" style="margin-left: 20px;">新增行</el-button>
        <el-button type="success" @click="exportData">导出</el-button>
        <input type="file" ref="fileInput" @change="importData" accept=".json" style="display: none;">
        <el-button type="warning" @click="$refs.fileInput.click()">导入</el-button>
        <el-button type="danger" @click="deleteSelectedRows" :disabled="!hasSelection">删除选中</el-button>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table :data="tableData" border :row-key="getRowKey" :highlight-current-row="!isMultiSelect" @current-change="handleCurrentChange" @selection-change="handleSelectionChange" height="500" style="width: 100%">
      <!-- 选择列 -->
      <el-table-column v-if="isMultiSelect" type="selection" width="55" reserve-selection />
      <el-table-column v-else label="选择" width="55">
        <template #default="scope">
          <el-radio v-model="currentRow" :label="scope.row" @change="handleRadioChange(scope.row)">&nbsp;</el-radio>
        </template>
      </el-table-column>

      <!-- 序号列 -->
      <el-table-column type="index" label="#" width="50" />

      <!-- 普通输入框列 -->
      <el-table-column prop="name" label="姓名" width="150">
        <template #default="scope">
          <el-input v-model="scope.row.name" placeholder="请输入姓名" size="small" />
        </template>
      </el-table-column>

      <!-- 下拉选择框列 -->
      <el-table-column prop="status" label="状态" width="150">
        <template #default="scope">
          <el-select v-model="scope.row.status" placeholder="请选择状态" size="small" style="width: 100%">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </template>
      </el-table-column>

      <!-- 数字输入框列 -->
      <el-table-column prop="age" label="年龄" width="120">
        <template #default="scope">
          <el-input-number v-model="scope.row.age" :min="0" :max="150" controls-position="right" size="small" style="width: 100%" />
        </template>
      </el-table-column>

      <!-- 普通输入框列 (城市) -->
      <el-table-column prop="city" label="城市" width="150">
        <template #default="scope">
          <el-input v-model="scope.row.city" placeholder="请输入城市" size="small" />
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button size="small" type="danger" @click="deleteRow(scope.$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 调试信息 -->
    <!--
    <div style="margin-top: 20px;">
      <p><strong>当前行 (单选):</strong> {{ currentRow ? currentRow.id : '无' }}</p>
      <p><strong>选中行 (多选):</strong> {{ selectedRows.map(r => r.id).join(', ') }}</p>
      <p><strong>表格数据:</strong></p>
      <pre>{{ JSON.stringify(tableData, null, 2) }}</pre>
    </div>
    -->
  </div>
</template>

<script setup>
import { ref, reactive, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// --- 数据定义 ---

// 表格数据
const tableData = ref([
  { id: 1, name: '张三', status: 'active', age: 25, city: '北京' },
  { id: 2, name: '李四', status: 'inactive', age: 30, city: '上海' },
  { id: 3, name: '王五', status: 'pending', age: 28, city: '广州' }
])

// 下拉选项
const statusOptions = [
  { value: 'active', label: '活跃' },
  { value: 'inactive', label: '非活跃' },
  { value: 'pending', label: '待定' }
]

// 选择模式
const isMultiSelect = ref(false) // true为多选，false为单选

// 单选时的当前行
const currentRow = ref(null)

// 多选时的选中行
const selectedRows = ref([])

// 文件输入引用
const fileInput = ref()

// --- 计算属性 ---
const hasSelection = computed(() => {
  return isMultiSelect.value ? selectedRows.value.length > 0 : !!currentRow.value
})

// --- 方法定义 ---

// 获取行的唯一key
const getRowKey = row => {
  return row.id
}

// 处理选择模式切换
const handleSelectModeChange = newMode => {
  // 切换模式时清空之前的选择状态
  if (newMode) {
    // 切换到多选
    currentRow.value = null
  } else {
    // 切换到单选
    selectedRows.value = []
    // 如果之前有选中行，可以默认选中第一行
    if (tableData.value.length > 0) {
      nextTick(() => {
        // 确保DOM更新后设置
        handleCurrentChange(tableData.value[0])
      })
    }
  }
}

// 处理单选变化
const handleCurrentChange = row => {
  if (!isMultiSelect.value) {
    currentRow.value = row
  }
}

const handleRadioChange = row => {
  // 当点击radio时，更新currentRow
  currentRow.value = row
}

// 处理多选变化
const handleSelectionChange = rows => {
  if (isMultiSelect.value) {
    selectedRows.value = rows
  }
}

// 新增行
const addNewRow = () => {
  const newRow = {
    id: Date.now(), // 使用时间戳作为临时ID
    name: '',
    status: '', // 默认为空，对应placeholder
    age: null, // 数字输入框初始为null
    city: ''
  }
  tableData.value.unshift(newRow) // 在第一行插入

  // 如果是单选模式，新增后自动选中新行
  if (!isMultiSelect.value) {
    nextTick(() => {
      handleCurrentChange(newRow)
    })
  }
}

// 删除指定行
const deleteRow = index => {
  const rowToDelete = tableData.value[index]
  let message = `确定要删除"${rowToDelete.name || '该行'}"吗？`

  ElMessageBox.confirm(message, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      tableData.value.splice(index, 1)
      ElMessage.success('删除成功')

      // 更新选中状态
      if (isMultiSelect.value) {
        const selectedIndex = selectedRows.value.findIndex(r => r.id === rowToDelete.id)
        if (selectedIndex > -1) {
          selectedRows.value.splice(selectedIndex, 1)
        }
      } else {
        if (currentRow.value && currentRow.value.id === rowToDelete.id) {
          currentRow.value = null
          // 如果删除的是当前行且还有其他行，可以选中下一行或第一行
          if (tableData.value.length > 0) {
            nextTick(() => {
              handleCurrentChange(tableData.value[0])
            })
          }
        }
      }
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 删除选中行
const deleteSelectedRows = () => {
  if (!hasSelection.value) return

  let message
  if (isMultiSelect.value) {
    message = `确定要删除选中的 ${selectedRows.value.length} 项吗？`
  } else {
    message = `确定要删除"${currentRow.value.name || '该项'}"吗？`
  }

  ElMessageBox.confirm(message, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      if (isMultiSelect.value) {
        const idsToDelete = selectedRows.value.map(r => r.id)
        tableData.value = tableData.value.filter(item => !idsToDelete.includes(item.id))
        selectedRows.value = []
        ElMessage.success(`成功删除 ${idsToDelete.length} 项`)
      } else {
        const index = tableData.value.findIndex(item => item.id === currentRow.value.id)
        if (index > -1) {
          tableData.value.splice(index, 1)
          ElMessage.success('删除成功')
          currentRow.value = null
          // 尝试选中下一行或第一行
          if (tableData.value.length > 0) {
            nextTick(() => {
              handleCurrentChange(tableData.value[0])
            })
          }
        }
      }
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 导出数据
const exportData = () => {
  const dataStr = JSON.stringify(tableData.value, null, 2)
  const dataUri = 'data:application/json;charset=utf-8,' + encodeURIComponent(dataStr)

  const exportFileDefaultName = 'table_data.json'

  const linkElement = document.createElement('a')
  linkElement.setAttribute('href', dataUri)
  linkElement.setAttribute('download', exportFileDefaultName)
  linkElement.click()
}

// 导入数据
const importData = event => {
  const file = event.target.files[0]
  if (!file) return

  const reader = new FileReader()
  reader.onload = e => {
    try {
      const jsonData = JSON.parse(e.target.result)
      if (Array.isArray(jsonData)) {
        // 简单验证数据结构，确保有id
        const validData = jsonData.map((item, index) => ({
          id: item.id || Date.now() + index, // 如果没有id则生成一个
          name: item.name || '',
          status: item.status || '',
          age: item.age !== undefined ? item.age : null,
          city: item.city || ''
        }))
        tableData.value = validData
        currentRow.value = null
        selectedRows.value = []
        ElMessage.success('数据导入成功')
        // 如果是单选模式且导入后有数据，选中第一行
        if (!isMultiSelect.value && tableData.value.length > 0) {
          nextTick(() => {
            handleCurrentChange(tableData.value[0])
          })
        }
      } else {
        throw new Error('导入的数据格式不正确，应为数组')
      }
    } catch (error) {
      console.error('导入失败:', error)
      ElMessage.error('导入失败: ' + (error.message || '文件内容无效'))
    } finally {
      // 重置文件输入，以便下次选择同一文件也能触发change事件
      event.target.value = ''
    }
  }
  reader.onerror = () => {
    ElMessage.error('读取文件时发生错误')
    event.target.value = ''
  }
  reader.readAsText(file)
}
</script>





